package com.wuyou.sso2.handler;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.wuyou.sso.common.utils.IdWorker;
import com.wuyou.sso.common.entity.LoginLog;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

/**
 * 默认认证成功处理器
 *
 * @author lishangbu
 * @date 2018/10/8
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class CustomizedAuthenticationSuccessEventHandler implements AuthenticationSuccessHandler {

    /**
     * IP 工具类
     */
//    private final Ip2regionSearcher regionSearcher;

    /**
     * 处理登录成功方法
     *
     * <p>获取到登录的authentication 对象
     *
     * @param authentication 登录对象
     * @param request        请求
     * @param response       返回
     */
    @Async
    @Override
    public void handle(
            Authentication authentication, HttpServletRequest request, HttpServletResponse response) {
        LoginLog loginLog = LoginLog.builder()
                .id(IdWorker.snowflakeId())
                .accountName(authentication.getName())
                .userAgent(request.getHeader(HttpHeaders.USER_AGENT))
                .loginTime(LocalDateTime.now())
                .exception(StrUtil.EMPTY)
                .remoteAddress(ServletUtil.getClientIP(request))
                .success(Boolean.TRUE)
                .build();
        UserAgent userAgent = UserAgentUtil.parse(loginLog.getUserAgent());
        loginLog.setOs(userAgent.getOs().getName());
        loginLog.setPlatform(userAgent.getPlatform().getName());
//        IpInfo ipInfo = regionSearcher.binarySearch(loginLog.getRemoteAddress());
//        if (ipInfo != null) {
//            loginLog.setRegion(ipInfo.getAddress());
//        }
//        LogUtils.buildLoginLog(loginLog);
    }
}
